package lexer;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/**
 * 读取文件的字符的类
 */
public class Reader {
    private String file = null; // 源程序
    StringBuffer buffer;// 缓冲区
    // abc    nowCh=' ' pos=0
    // 012    nowCh=a  pos=1
    char nowCh = ' '; //当前读到的字符
    int pos = 0; //下一个字符的位置

    public Reader() {
        buffer = new StringBuffer();
    }

    public Reader(String file) {
        this.file = file;
        this.buffer = new StringBuffer();
    }

    public void readFile() {
        if (file != null) {
            try {
                FileReader fileReader = new FileReader(this.file);
                BufferedReader bufferedReader = new BufferedReader(fileReader);
                String tmp = null;
                while ((tmp = bufferedReader.readLine()) != null) {
                    buffer.append(tmp);
                    buffer.append('\n');
                }
                bufferedReader.close();
                fileReader.close();
            } catch (FileNotFoundException e) {
                System.out.println("没有找到这个源文件");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("读写文件异常");
                e.printStackTrace();
            }
        } else {
            System.out.println("---控制台输入模式---");
            Scanner scanner = new Scanner(System.in);
            String tmp = null;
            while ((tmp = scanner.nextLine()) != null) {
                if (tmp.equals("-1"))
                    break;
                buffer.append(tmp);
                buffer.append('\n');
            }
            System.out.println(buffer);
        }
    }

    public char nextChar() { // 只获取下一个字符的内容
        if (!isEOF()) {
            return this.buffer.charAt(pos);
        }
        return 0;
    }

    public char getChar() {//读取下一个字符
        if (!isEOF()) {
            this.nowCh = this.buffer.charAt(pos);
            this.pos++;
            return this.nowCh;
        }
        return 0;
    }

    // abc    nowCh=null pos=0
    // 012    nowCh=a  pos=1
    public void rollbackChar() {//回退一个字符
        this.pos--;
        if (pos != 0)
            this.nowCh = this.buffer.charAt(pos - 1);
        else
            this.nowCh = ' ';
    }

    public Boolean isEOF() { //是否到文件末尾
        return pos >= buffer.length();
    }
}
